<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>无限盲盒信息</span>
      </div>
      <!-- 图表 -->

      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
        <el-row>
          <el-col :span="6">
            <el-form-item label="盲盒等级" prop="clevel">
              <el-select style="width:360px" v-model="form.clevel" placeholder="请选择是否预售">
                <el-option label="普通" value="1"></el-option>
                <el-option label="中级" value="2"></el-option>
                <el-option label="高级" value="3"></el-option>
              </el-select>
              <!-- <el-input v-model="form.clevel" style="width:360px" placeholder="请输入盲盒名称"></el-input> -->
            </el-form-item>
            <el-form-item label="盲盒名称" prop="name">
              <el-input v-model="form.name" style="width:360px" placeholder="请输入盲盒名称"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="盲盒封面" prop="img">
                  <el-upload
                    class="avatar-uploader"
                    action="https://upload-z0.qiniup.com/"
                    :data="postData"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详情页图" prop="details_img">
                  <el-upload
                    class="avatar-uploader"
                    action="https://upload-z0.qiniup.com/"
                    :data="postData"
                    :show-file-list="false"
                    :on-success="handleSuccess"
                    :before-upload="beforeUpload"
                  >
                    <img v-if="detailUrl" :src="detailUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="是否狂欢模式" prop="isMiaowa" v-if="form.pay_type ==1">
              <el-radio-group v-model="form.isMiaowa">
                <el-radio label="1" :value="true">是</el-radio>
                <el-radio label="0" :value="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.isMiaowa==1" label="狂欢模式发数" prop="mw_num">
              <el-input-number v-model="form.mw_num" :min="1" label="双倍模式发数"></el-input-number>
            </el-form-item>
            <el-form-item v-if="form.isMiaowa==1" label="狂欢模式持续时间（小时）" prop="resource">
              <el-input-number
                v-model="form.mw_time"
                :precision="1"
                :step="0.1"
                :min="1"
                label="狂欢模式持续时间"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="流水限制" prop="is_ls">
              <el-input style="width:360px" v-model="form.is_ls" placeholder="输入0为无限制"></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input style="width:360px" v-model="form.price" placeholder="请输入单价"></el-input>
            </el-form-item>
            <el-form-item label="抽取方式" prop="pattern">
              <el-select style="width:360px" v-model="form.pattern" placeholder="请选择抽取方式">
                <el-option label="单抽" value="1"></el-option>
                <el-option label="不单抽" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否预售" prop="is_ys">
              <el-select style="width:360px" v-model="form.is_ys" placeholder="请选择是否预售">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预售时间" prop="is_ys">
              <el-date-picker
                style="width:360px"
                :disabled="form.is_ys==0"
                v-model="form.ys_time"
                type="datetime"
                placeholder="选择预售时间"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="支付方式">
              <el-select style="width:360px" v-model="form.pay_type" placeholder="请选择支付方式">
                <el-option label="正常支付" value="1"></el-option>
                <el-option label="积分支付" value="2"></el-option>
                <el-option label="道具支付" value="3"></el-option>
              </el-select>
              <!-- <el-radio-group v-model="form.pay_type">
                <el-radio label="1" :value="true"></el-radio>
                <el-radio label="2" :value="false"></el-radio>
                <el-radio label="3" :value="false"></el-radio>
              </el-radio-group>-->
            </el-form-item>
            <el-form-item label="支付道具" v-if="form.pay_type==3">
              <!-- goods_id -->
              <el-button type="primary" @click="singleVisible = true">选择道具</el-button>
              <span style="margin-left: 4px" v-if="goodsPay.goods_name">{{ goodsPay.goods_name }}</span>
              <img v-if="goodsPay.img" :src="goodsPay.img" style="width:100px;height:100px" />
            </el-form-item>
            <el-form-item v-if="form.pay_type ==1" label="是否产生积分" prop="is_integral">
              <el-select style="width:360px" v-model="form.is_integral" placeholder="请选择是否产生积分">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.pay_type ==1" label="积分数量" prop="integral">
              <el-input
                style="width:360px"
                :disabled="form.is_integral==0"
                v-model="form.integral"
                placeholder="请输入积分数量"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <div>收入：{{form.income=(10000*form.price).toFixed(2)}}</div>
              <div>实际成本：{{form.cost}} 价格成本：{{form.price_cost}}</div>
              <div>实际利润：{{form.profit=(Number(form.income)-Number(form.cost)).toFixed(2)||'0'}} 价格利润：{{form.price_profit=(Number(form.income)-Number(form.price_cost)).toFixed(2)||'0'}}</div>
              <div>实际利润率：{{form.profit_lv=((Number(form.profit)/Number(form.cost))*100).toFixed(2)||'0'}}% 价格利润率：{{form.price_profit_lv=((Number(form.price_profit )/Number(form.price_cost))*100).toFixed(2)||'0'}}%</div>
              <div>
                概率展示：
                <span
                  style="margin-right:20px"
                  v-for="(item,index) in probabilityList"
                  :key="index"
                  v-show="item.probability!=0"
                >
                  {{item.name}}
                  {{item.probability+'%'}}
                </span>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="WXonSubmit">立即创建</el-button>
              <el-button @click="WXCancel">取消</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="选择奖品" prop="goods_data">
              <el-button size="small" type="primary" round @click="addRewards">添加奖品</el-button>
              <el-table
                :header-cell-style="{background:'#eee'}"
                :data="form.goods_data"
                border
                style="width: 100%;margin-bottom: 20px;"
              >
                <el-table-column type="index" width="50" align="center"></el-table-column>
                <el-table-column align="center" prop="goods_name" label="奖品名称">
                  <template slot-scope="scope">
                    <el-popover placement="top-start" title trigger="hover">
                      <p>{{scope.row.goods_name}}</p>
                      <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                      <!-- <el-avatar shape="square" :size="50" fit="scale-down" :src="scope.row.img"></el-avatar> -->
                      <p slot="reference">{{scope.row.goods_name.substring(0,25)}}</p>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="奖品图片" width="80px">
                  <template slot-scope="scope">
                    <el-popover placement="top-start" title trigger="hover">
                      <img :src="scope.row.img" alt style="max-width:150px" />
                      <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                      <el-avatar
                        slot="reference"
                        shape="square"
                        :size="50"
                        fit="scale-down"
                        :src="scope.row.img"
                      ></el-avatar>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="中奖名称" width="120px">
                  <template slot-scope="scope">
                    <el-select :loading="ruleLoading" v-model="scope.row.rule_id" placeholder="请选择">
                      <el-option
                        v-for="(item,index) in ruleoptions"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="概率" width="120px">
                  <template slot-scope="scope">
                    <el-input
                      @change="probabilityChange"
                      v-model="scope.row.probability"
                      placeholder="请输入概率最多三位小数"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="测试发数" width="120px">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.is_con" placeholder="请选择是否测试">
                      <el-option label="是" value="1"></el-option>
                      <el-option label="否" value="0"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="阶段发数" width="180px">
                  <template slot-scope="scope">
                    <div style="display:flex;align-items:center">
                      <el-input
                        :disabled="scope.row.is_con!=1"
                        v-model="scope.row.con_start"
                        placeholder="开始"
                        @change="lowChange(scope.row)"
                      ></el-input>-
                      <el-input
                        :disabled="scope.row.is_con!=1"
                        v-model="scope.row.con_end"
                        placeholder="结束"
                        @change="heightChange(scope.row)"
                      ></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="价格" prop="price" width="120px"></el-table-column>
                <el-table-column align="center" label="成本" prop="y_price" width="120px"></el-table-column>
                <el-table-column align="center" fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-popconfirm
                      confirmButtonText="好的"
                      cancelButtonText="不用了"
                      icon="el-icon-info"
                      iconColor="red"
                      title="这是一段内容确定删除吗？"
                      @onConfirm="handleDel(scope.row)"
                    >
                      <el-button slot="reference" type="text" size="small">删除</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
                <el-table-column align="center" fixed="right" label="排序" width="160">
                  <template slot-scope="scope">
                    <el-button
                      @click="goFirst(scope.row)"
                      slot="reference"
                      type="text"
                      size="small"
                    >
                      <i class="el-icon-top" style="font-size:25px"></i>
                    </el-button>
                    <el-button @click="goUp(scope.row)" slot="reference" type="text" size="small">
                      <i class="el-icon-upload2" style="font-size:25px"></i>
                    </el-button>
                    <el-button @click="goDown(scope.row)" slot="reference" type="text" size="small">
                      <i class="el-icon-download" style="font-size:25px"></i>
                    </el-button>
                    <el-button @click="goLast(scope.row)" slot="reference" type="text" size="small">
                      <i class="el-icon-bottom" style="font-size:25px"></i>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="query" :model="query" label-width="80px">
        <el-form-item label="奖品名称">
          <el-input v-model="query.keywords" placeholder="请输入奖品名称"></el-input>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input v-model="query.lowPrice" style="width:50px" placeholder="低"></el-input>-
          <el-input v-model="query.heightPrice" style="width:50px" placeholder="高"></el-input>
        </el-form-item>
        <el-form-item label="奖品分类">
          <el-cascader
            @focus="getBoxRewardTypeList"
            v-model="query.class_id"
            :options="queryOptioins"
            :props="{ checkStrictly: true,value:'id',label:'class_name' }"
            placeholder="请选择奖品分类"
            clearable
            :loading="queryLoading"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryAsk">筛选</el-button>
          <el-button @click="queryReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        @sort-change="sortChange"
        ref="multipleTable"
        :header-cell-style="{background:'#eee'}"
        :data="boxRewardData"
        v-loading="loading"
        border
        style="width: 100%;margin-bottom: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="id" label="ID"></el-table-column>
        <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
        <el-table-column align="center" label="奖品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="y_price" label="成本"></el-table-column>
        <el-table-column align="center" prop="price" label="价格" sortable="custom"></el-table-column>
        <el-table-column align="center" prop="address" label="预售/现货">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">预售</div>
            <div v-if="scope.row.type==2">现货</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="是否参与合成材料">
          <template slot-scope="scope">
            <div v-if="scope.row.is_compound==1">可以</div>
            <div v-if="scope.row.is_compound==0">不可以</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="compound_price" label="合成数值"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>

      <div style="margin-top:20px;float:right">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="subCancel">取消</el-button>
      </div>
    </el-drawer>

    <el-dialog title="选择奖品" :visible.sync="singleVisible" width="60%" :before-close="handleClose">
      <singleTable v-if="singleVisible" @getPayGood="getPayGood" @singCancel="singCancel"></singleTable>
    </el-dialog>
  </div>
</template>

<script>
import { upload } from '@/api/system'
import { boxRewardList, boxRewardTypeList } from '@/api/boxreward'
import { categoryList } from '@/api/product'
import { addWXBox, boxinfo, editWXBox } from '@/api/blindbox'
import { rewardList } from '@/api/system'
import { parseTime } from '@/utils/index'
import singleTable from '@/components/singleTable'

export default {
  name: 'AddBoxWX',
  components: { singleTable },
  data() {
    return {
      title: '添加',
      formLoading: false,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: '',
        class_id: '0',
        lowPrice: '',
        heightPrice: '',
        order_by: ''
      },
      boxRewardData: [],
      goodsObj: {},
      form: {
        clevel: '',
        pay_type: 1,
        isMiaowa: '0',
        mw_num: 1,
        mw_time: '',
        name: '',
        img: '',
        details_img: '',
        class_id: '0',
        describe: '',
        price: '',
        pattern: '',
        sort: '',
        is_ls: '',
        is_tui: '',
        is_ys: '',
        ys_time: '',
        is_integral: '',
        integral: '0',
        goods_data: [],
        income: '',
        cost: '',
        profit: '',
        profit_lv: ''
      },
      rules: {
        name: [{ required: true, message: '请输入盲盒名称', trigger: 'blur' }],
        img: [{ required: true, message: '请上传封面图片', trigger: 'blur' }],
        details_img: [
          { required: true, message: '请上传详情图片', trigger: 'blur' }
        ],
        class_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        price: [{ required: true, message: '请输入奖单价', trigger: 'blur' }],
        extract_ci: [
          { required: true, message: '请输入单箱抽取次数', trigger: 'blur' }
        ],
        is_ls: [{ required: true, message: '请输入流水限制', trigger: 'blur' }],
        pattern: [
          { required: true, message: '请选择抽取方式', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        is_tui: [
          { required: true, message: '请选择是否推荐', trigger: 'blur' }
        ],
        is_cc: [
          { required: true, message: '请选择是否存在冲冲赏', trigger: 'blur' }
        ],
        is_integral: [
          { required: true, message: '请输选择是否产生积分', trigger: 'blur' }
        ],
        integral: [
          { required: true, message: '请输入积分数量', trigger: 'blur' }
        ],
        goods_data: [{ required: true, message: '请选择奖品', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      detailUrl: '',
      // 编辑抽屉
      drawer: false,
      direction: 'rtl',
      title: '奖品',
      loading: false,
      priceArr: [],
      queryLoading: false,
      queryOptioins: [],
      //添加奖品列表
      selectArr: [],
      ruleoptions: [],
      ruleLoading: false,
      totalnum: 0,
      probabilityList: [],
      classId: '0',
      singleVisible: false,
      goodsPay: {}
    }
  },
  mounted() {
    this.form.ys_time = new Date()
    this.title = this.$route.query.title
    if (this.title == '添加') {
      this.getrule()
    }
    this.getToken()
    if (this.title == '编辑') {
      this.getTXinfo()
    }
  },
  activated() {
    this.form.ys_time = new Date()
    this.title = this.$route.query.title
    if (this.title == '添加') {
      this.getrule()
    }
    this.getToken()
    if (this.title == '编辑') {
      this.getTXinfo()
    }
  },
  methods: {
    singCancel() {
      this.singleVisible = false
    },
    getPayGood(e) {
      console.log(e)
      this.goodsPay = e
      this.form.goods_id = e.id
      this.singleVisible = false
    },
    // 获取详细信息
    async getTXinfo() {
      await this.getrule()
      this.probabilityList = []
      this.ruleoptions.forEach((item) => {
        const gl = {
          id: item.id,
          name: item.name,
          probability: 0
        }
        this.probabilityList.push(gl)
      })
      this.formLoading = true
      const res = await boxinfo({ id: this.$route.query.id })
      this.formLoading = false
      console.log(res)
      this.form = res.data
      this.imageUrl = res.data.img
      this.detailUrl = res.data.details_img
      this.goodsPay = res.data.goodsPay
      // 回显概率展示
      console.log('gl')

      console.log(this.probabilityList)
      this.probabilityList.forEach((item) => {
        res.data.probability_show.forEach((prob) => {
          if (prob[item.name] != undefined) {
            item.probability = prob[item.name]
          }
        })
      })
      console.log(this.probabilityList)
      // 概率去除最后的0
      // this.form.goods_data.forEach(item => {
      //   item.probability = this.removeTrailingZeros(item.probability);
      // });
    },
    // 去除小数最后的0
    removeTrailingZeros(num) {
      const str = num.toString()
      return str.indexOf('.') !== -1 ? str.replace(/\.?0*$/, '') : str
    },
    WXonSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.form.is_ys == 0) {
            this.form.ys_time = 0
          } else {
            this.form.ys_time = parseTime(this.form.ys_time)
          }
          let probability = 0
          this.form.goods_data.forEach((item) => {
            probability = Number(
              (probability += Number(item.probability)).toFixed(3)
            )
          })
          if (probability != 100) {
            this.$message.error('所有中奖概率不等于百分百！' + probability)
            return
          }
          // 检查表中数据有无漏填
          for (let i = 0; i < this.form.goods_data.length; i++) {
            if (!this.form.goods_data[i].rule_id) {
              this.$message.error('请选择中奖名称！')
              return
            }
            // else if (this.form.goods_data[i].is_con == 1) {
            //   if (
            //     this.form.goods_data[i].stage_start == 0 ||
            //     this.form.goods_data[i].stage_end == 0
            //   ) {
            //     this.$message.error("请检查阶段数填写！");
            //     return;
            //   }
            // }
            else if (this.form.is_integral == 1) {
              if (this.form.integral == 0) {
                this.$message.error('产生积分积分不能为0！')
                return
              }
            }
          }
          if (this.title == '添加') {
            const pushForm = Object.assign({}, this.form, {
              // pay_type =2 积分支付
              is_integral: this.form.pay_type == 2 ? 0 : this.form.is_integral,
              integral: this.form.pay_type == 2 ? 0 : this.form.integral,
              isMiaowa: this.form.pay_type == 2 ? 0 : this.form.isMiaowa,
              price: this.form.pay_type == 3 ? 1 : this.form.price
            })
            const res = await addWXBox({ ...pushForm })
            if (res.st == 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          } else if (this.title == '编辑') {
            const pushForm = Object.assign({}, this.form, {
              // pay_type =2 积分支付
              is_integral: this.form.pay_type == 2 ? 0 : this.form.is_integral,
              integral: this.form.pay_type == 2 ? 0 : this.form.integral,
              isMiaowa: this.form.pay_type == 2 ? 0 : this.form.isMiaowa,
              price: this.form.pay_type == 3 ? 1 : this.form.price
            })
            const res = await editWXBox({ ...pushForm })
            if (res.st == 1) {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          }
        }
      })
    },
    WXCancel() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      //返回上一个tab页面 返回上一步路由，
      this.$router.go(-1)
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },
    handleSuccess(res, file) {
      this.detailUrl = this.url + res.key
      this.form.details_img = this.detailUrl
    },
    beforeUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },
    async getToken() {
      const res = await upload()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    //抽屉
    handleClose(done) {
      this.drawer = false
      done()
    },
    subCancel() {
      this.drawer = false
    },
    //分页改变
    async currentChange(current) {
      this.currentPage = current
      await this.getBoxRewardList()
      const select = []
      console.log(this.form.goods_data)
      if (this.form.goods_data) {
        this.form.goods_data.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
    },
    // 添加奖品
    async addRewards() {
      this.drawer = true
      await this.getBoxRewardList()
      const select = []
      console.log(this.form.goods_data)
      if (this.form.goods_data) {
        this.form.goods_data.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
      this.selectArr = this.form.goods_data
    },
    //获取奖品列表
    async getBoxRewardList() {
      this.loading = true
      const res = await boxRewardList({
        page: this.currentPage,
        limit: this.pageSize,
        class_id: this.classId,
        price: this.priceArr,
        keywords: this.query.keywords,
        order_by: this.query.order_by
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.boxRewardData = res.data
    },
    //获取奖品分类列表
    async getBoxRewardTypeList() {
      this.queryLoading = true
      const res = await categoryList({
        page: '1',
        limit: '999',
        keywords: ''
      })
      this.queryLoading = false
      console.log(res)
      this.queryOptioins = res.data
    },
    // 搜索列表
    queryAsk() {
      // 不可以一个有值一个没值
      if (!this.query.lowPrice && !this.query.heightPrice) {
        console.log(this.query)
        this.priceArr = []
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (this.query.lowPrice && this.query.heightPrice) {
        this.priceArr = [this.query.lowPrice, this.query.heightPrice]
        console.log(this.query)
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (!this.query.lowPrice || !this.query.heightPrice) {
        this.$message.error('请输入价格区间')
      }
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.query.lowPrice = ''
      this.query.heightPrice = ''
      this.query.order_by = ''
      this.query.class_id = '0'
      this.classId = '0'
      this.getBoxRewardList()
    },
    // 选择奖品
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    handleSelectionChange(val) {
      this.selectArr = []
      //已经有的不添加
      const aIds = new Set(this.selectArr.map((item) => item.id))
      val.forEach((item) => {
        if (!aIds.has(item.id)) {
          this.selectArr.push(item)
        }
      })
    },
    onSubmit() {
      console.log(this.form.goods_data)
      const aIds = new Set(this.form.goods_data.map((item) => item.goods_id))
      this.selectArr.forEach((item) => {
        if (!aIds.has(item.id)) {
          const dx = {
            goods_id: item.id,
            rule_id: '',
            sort: '',
            num: '0',
            win_type: '-1',
            stage_start: '0',
            stage_end: '0',
            img: item.img,
            goods_name: item.goods_name,
            price: item.price,
            y_price: item.y_price,
            id: '0'
          }
          this.form.goods_data.unshift(dx)
        }
      })
      this.form.goods_data.sort((a, b) => b.price - a.price)
      this.form.goods_data.forEach((item, index) => {
        console.log(index)
        item.sort = this.form.goods_data.length - (index + 1)
      })
      console.log(this.form.goods_data)
      // this.selectArr.forEach(item => {
      //   if (!aIds.has(item.id)) {
      //     const dx = {
      //       goods_id: item.id,
      //       rule_id: "",
      //       sort: "",
      //       num: "0",
      //       con_start: "0",
      //       con_end: "0",
      //       img: item.img,
      //       goods_name: item.goods_name,
      //       price: item.price,
      //       y_price: item.y_price,
      //       is_con: "0",
      //       id: "0"
      //     };
      //     if (this.form.goods_data.length == 0) {
      //       dx.sort = 0;
      //     } else {
      //       console.log(this.form.goods_data[0].sort);
      //       dx.sort = Number(this.form.goods_data[0].sort) + 1;
      //     }
      //     this.form.goods_data.unshift(dx);
      //   }
      // });
      // console.log(this.form.goods_data);
      this.drawer = false
    },
    async getrule() {
      this.ruleLoading = true
      const res = await rewardList({
        page: '1',
        limit: '999',
        keywords: '',
        type: '2'
      })
      this.ruleoptions = res.data
      this.ruleoptions.forEach((item) => {
        const gl = {
          id: item.id,
          name: item.name,
          probability: 0
        }
        this.probabilityList.push(gl)
      })
      this.ruleLoading = false
    },
    probabilityChange() {
      this.form.cost = 0
      this.form.price_cost = 0
      // 每次改变重新计算
      this.probabilityList.forEach((item) => {
        item.probability = 0
      })
      this.form.goods_data.forEach((item) => {
        // 成本
        let cost = Number(
          Number(
            (10000 * (Number(item.probability) / 100) * item.y_price).toFixed(2)
          )
        )
        // 价格
        let price_cost = Number(
          Number(
            (10000 * (Number(item.probability) / 100) * item.price).toFixed(2)
          )
        )
        this.form.cost = Number((this.form.cost += cost).toFixed(2))
        this.form.price_cost = Number(
          (this.form.price_cost += price_cost).toFixed(2)
        )

        this.probabilityList.forEach((prob) => {
          if (item.rule_id == prob.id) {
            console.log(item.probability)
            if (item.probability != undefined) {
              prob.probability += Number(Number(item.probability).toFixed(3))
              prob.probability = Number(prob.probability.toFixed(3))
            }
          }
        })
      })
      console.log(this.probabilityList)
    },
    lowChange(row) {
      if (row.con_end != 0) {
        if (Number(row.con_start) > Number(row.con_end)) {
          row.con_start = '1'
          this.$message.error('开始不能大于结束')
        }
      }
    },
    heightChange(row) {
      if (Number(row.con_start) > Number(row.con_end)) {
        row.con_end = ''
        this.$message.error('结束不能小于开始')
      }
    },
    handleDel(row) {
      this.form.goods_data.forEach((good, index) => {
        if (good.goods_id == row.goods_id) {
          this.form.goods_data.splice(index, 1)
        }
      })
    },
    // 图表排序
    goFirst(row) {
      row.sort = this.form.goods_data[0].sort
      let index = this.form.goods_data.indexOf(row)
      let item = this.form.goods_data.splice(index, 1)[0] // 从数组中移除该项并获得它
      this.form.goods_data.unshift(item) // 将该项插入到数组的开头
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = this.form.goods_data[0].sort - i
      }
    },
    goUp(row) {
      let index = this.form.goods_data.indexOf(row)

      if (index > 0) {
        this.form.goods_data.splice(
          index - 1,
          0,
          this.form.goods_data.splice(index, 1)[0]
        )
      }
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    goDown(row) {
      let index = this.form.goods_data.indexOf(row)
      if (index < this.form.goods_data.length - 1) {
        this.form.goods_data.splice(
          index + 1,
          0,
          this.form.goods_data.splice(index, 1)[0]
        )
      }
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    goLast(row) {
      row.sort = this.form.goods_data[this.form.goods_data.length - 1].sort
      let index = this.form.goods_data.indexOf(row)
      let item = this.form.goods_data.splice(index, 1)[0] // 从数组中移除该项并获得它
      this.form.goods_data.push(item) // 将该项插入到数组的末尾
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    // 排序
    sortChange({ column, prop, order }) {
      if (order == 'descending') {
        this.query.order_by = prop + ',' + 'desc'
        this.getBoxRewardList()
      } else if (order == 'ascending') {
        this.query.order_by = prop + ',' + 'asc'
        this.getBoxRewardList()
      }
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
  .el-form {
    display: flex;
    flex-wrap: wrap;
  }
}
::v-deep .el-textarea__inner {
  width: 360px !important;
}
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 800px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 158px;
  line-height: 158px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>